

import axios from 'axios';
import Vue from 'vue'
import store from '@/store';
import qs from 'qs';
import router from '@/router'
import {
  baseURL,
  questTimeout,
  successCode,
  invalidCode,
  tokenName,
  noPermissionCode
} from '@/config/settings'

const instance = axios.create({
  baseURL,
  timeout: questTimeout
})

//  请求拦截
instance.interceptors.request.use(config => {
  if (config.getters['user/accessToken']) {
    config.headers[tokenName] = store.getters['user/accessToken']
  }
  return config
}, error => {
  return Promise.reject(error)
})
//  响应拦截
instance.interceptors.response.use(response => {
  const { status, data, config } = response
  const { code, msg } = data;
  if (successCode.includes(code)) {
    return data
  } else {
    handleCode(code, msg)
    return Promise.reject("请求拦截异常" + JSON.stringify({ url: config.url, code, msg }))
  }
}, error => {
  return Promise.reject(error)
})


/**
 *处理code异常
 * @param {*} code
 * @param {*} msg
 */
function handleCode(code, msg) {
  switch (code) {
    case invalidCode:
      store.dispatch("user/resetAccessToken")
      if (loginInterception) {
        location.reload();
      }
      break;
    case noPermissionCode:
      store.dispatch("user/resetAccessToken")
      if (loginInterception) {
        location.reload()
      }
      router.push({ path: "/401" })
      //  todo 清除字典数据
      break;
    default:
    // todo 错误提示
    // Vue.prototype.$base
  }
}

export default instance